#include "DoubleLinkList.h"
#include<iostream>

DoubleLinkList::DoubleLinkList():size(0)
{
    head = new Node(0);
    tail = head;
}


void DoubleLinkList::InsertTail(const ElementType &element)
{
    Node* newNode = new Node(element);
    tail->next = newNode;
    newNode->prev = tail;
    tail = newNode;
    
    this->size++;
}

void DoubleLinkList::InsertHead(const ElementType &element)
{
    Node *newNode = new Node(element);
    
    newNode->next = head->next;
    newNode->prev = head;
    head->next = newNode;
    
    if(size !=0)
    newNode->next->prev = newNode;
    else
    {
        tail = newNode;
    }
    size++;
}

void DoubleLinkList::InsertByIndex(int index,const ElementType &element) //中间插入
{
    Node* travelPoint = head; 
    for(int i=0;i < index;i++)
    {
        travelPoint = travelPoint->next;
    }
    
    Node* newNode = new Node(element); 
    
    newNode->next = travelPoint->next;
    newNode->prev = travelPoint;

    travelPoint->next = newNode;
    if(size != index)
    newNode->next->prev = newNode;
    else
    {
        tail = newNode;
    } 
    size++;




}



void DoubleLinkList::RemoveByIndex(int index)
{
    if(index<0 || index >= size)
    {
        std::cout<<"非法的删除位置\n";
        return;
    }

    Node* travelPoint = head;
    
    for(int i=0;i<index;i++)
    {
        travelPoint = travelPoint->next;
    }
    
    Node* freeNode = travelPoint->next;

    travelPoint->next = freeNode->next;
    
    if(size != index + 1)
    freeNode->next->prev = travelPoint;
    else
    {
        tail = travelPoint;
        travelPoint->next = nullptr;
    }  
    delete freeNode;
    size--;
}

void DoubleLinkList::RemoveElement(const ElementType &element)
{
    Node *travelPoint = head;
    while (travelPoint->next != nullptr)
    {
        if(travelPoint->next->data == element)
        {
            Node* freeNode = travelPoint->next;
            
            travelPoint->next = freeNode->next;

            if(freeNode->next == nullptr)
                {
                    tail = travelPoint;
                }
            if(freeNode->prev == head)
                {
                    freeNode->next->prev =head;
                }
            delete freeNode;
            size--; 
        }
        else
        travelPoint = travelPoint->next;
    }
}




DoubleLinkList::~DoubleLinkList()
{
        while(head != nullptr)
    {
        Node* nextNode = head ->next;//记下下一个结点
        delete head;
        head = nextNode;// 结点往后走
    }
}

void DoubleLinkList::show()
{   
    Node *travelPoint = head->next;
    std::cout<<this->size<<std::endl;
    while (travelPoint != nullptr)
    {   
        std::cout<<travelPoint->data<<" ";
        travelPoint = travelPoint->next;
    }
    std::cout<<std::endl;

    travelPoint = tail;
    while(travelPoint != head)
    {
        std::cout<<travelPoint->data<<" ";
        travelPoint = travelPoint->prev; 
    }
    std::cout<<std::endl;
}


